import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse

from utils.response_code import RETCODE
from utils.secret import serializer
from .models import User


# 自定义一个BackendsModel,用于多账号认证,支持手机号登陆
class UsernameMobileAuthenticate(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写父类的authenticate方法,使其支持手机号认证"""
        extra = {}
        if not request:
            extra['is_staff'] = True
        try:
            if re.match(r'^1[3-9]\d{9}$', username):  # 符合手机号的正则
                user = User.objects.get(mobile=username, **extra)
            else:
                user = User.objects.get(username=username, **extra)
        except User.DoesNotExist as e:
            settings.LOGGER.error(e)
            return None

        return user if user.check_password(password) else None


class LoginRequiredJsonMixin(LoginRequiredMixin):

    def handle_no_permission(self):
        return JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})


# 生成email认证链接
def generate_verify_email_url(user):
    verify_dict = {'id':user.id, 'email':user.email}
    secret_verify_dict = serializer.dumps(verify_dict).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + secret_verify_dict
    return verify_url
